package com.ruitu.mall_98_1.search;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.utils.SizeUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.NestedRecyclerView;
import com.ruitu.mall_98_1.R;
import com.ruitu.mall_98_1.dao.api.APIRetrofit;
import com.ruitu.mall_98_1.product.activity.ProductDetailActivity;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.DataAdapter;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.app.Area;
import com.ruitu.router_module.bean.app.HotWord;
import com.ruitu.router_module.bean.product.Category;
import com.ruitu.router_module.bean.product.Product;
import com.ruitu.router_module.bean.product.SearchData;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SearchActivity extends MyBaseActivity {
    private ViewPager vp;
    private TabLayout tab;
    private VpAdapter vpAdapter;
    private RecyclerView recyclerView;
    private NestedRecyclerView rcv_hot_list;//热搜关键字
    private ScrollView scrollView;

    private DataAdapter globalAdapter;
    private SearchData searchData;
    private List<Area> areaList = new ArrayList<>();//省市区列表
    private List<Category> categoryList = new ArrayList<>();//分类列表
    private List<HotWord> hotList = new ArrayList<>();
    private HotListAdapter adapter;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_search;
    }

    @Override
    protected void onRightTextClick() {
        Arad.bus.post(new EventModel(181121));//重置搜索条件
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vp = findViewById(R.id.vp);
        tab = findViewById(R.id.tab);
        recyclerView = findViewById(R.id.recyclerView);
        rcv_hot_list = findViewById(R.id.rcv_hot_list);
        scrollView = findViewById(R.id.scrollView);
        setHeadTitle("搜索条件");
        setRightText("重置");
        disableSlideBack();

        globalAdapter = new DataAdapter(this);
        setRecoProList();
        adapter = new HotListAdapter(this);
        FlowLayoutManager manager = new FlowLayoutManager() {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
//        rcv_hot_list.addItemDecoration(new SpaceItemDecoration(SizeUtils.dp2px(10)));
        rcv_hot_list.setLayoutManager(manager);
        rcv_hot_list.setAdapter(adapter);
        adapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                //点击热搜关键词 只搜索商品,而且和选些的地区,分类等信息无关
                Arad.bus.post(new EventModel(19030151, hotList.get(position).getKey()));
            }
        });
        vp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) vp.getLayoutParams();
                if (position == 0) {
                    params.height = SizeUtils.dp2px(255);
                } else {
                    params.height = SizeUtils.dp2px(205);
                }
                vp.setLayoutParams(params);
            }
        });

        showProgress();
        reqSearchData();
    }

    private void reqHotList() {//请求搜索结果列表
        APIRetrofit.getDefault().reqHotList()
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<List<HotWord>>>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseResult<List<HotWord>> baseResult) {
                        hideProgress();
                        hotList = baseResult.getData();
                        adapter.setDataList(hotList);
                    }
                });
    }

    //设置为您推荐商品列表
    private void setRecoProList() {
        GridLayoutManager manager1 = new GridLayoutManager(this, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        recyclerView.setLayoutManager(manager1);
        recyclerView.setAdapter(globalAdapter);
        globalAdapter.setDataList(AppHolder.instance().getGlobalProList());
        globalAdapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                try {
                    Bundle bundle = new Bundle();
                    Product product = new Product();
                    product.setGoodId(AppHolder.instance().getGlobalProList().get(position).getGoodsId());
                    bundle.putSerializable("product", product);
                    startActivity(ProductDetailActivity.class, bundle);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //请求搜索条件数据
    private void reqSearchData() {
        APIRetrofit.getDefault().reqSearchData("hehe")
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<SearchData>>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseResult<SearchData> searchDataResult) {
                        hideProgress();
                        if (searchDataResult.isSuccess()) {
                            areaList = searchDataResult.getData().getCityies();
                            categoryList = searchDataResult.getData().getClassificationList();
                            searchData = searchDataResult.getData();

                            vpAdapter = new VpAdapter(getSupportFragmentManager());
                            vp.setAdapter(vpAdapter);
                            tab.setupWithViewPager(vp);

                            scrollView.scrollTo(0, 0);
                            reqHotList();//搜索数据(地区和分类数据)请求完成,再获取热搜关键词
                        } else {
                            ToastUtils.showShort(searchDataResult.getMsg());
                        }
                    }
                });
    }

    private class VpAdapter extends FragmentPagerAdapter {

        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return SearchProFragment.newInstance(searchData);
            }
            return SearchShopFragment.newInstance(searchData);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (position == 0) {
                return "商品搜索";
            } else {
                return "企业搜索";
            }
        }
    }

    @Override
    public void onBackPressed() {
        UIUtils.hideInput(this, vp.getWindowToken());
        super.onBackPressed();
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }
}
